from fastapi import APIRouter, Depends, HTTPException, Query, Path
from fastapi.security import OAuth2PasswordRequestForm
from pydantic import BaseModel, Field

from ..core.response import Response
from ..core.exception import BusinessException
from ..models.user import User, Role
from app.schemas.user import UserCreate, UserOut, UserUpdate
from app.core.security import hash_password
from app.auth.auth import authenticate_user, create_token_response
from app.auth.deps import get_current_user, require_role

router = APIRouter(prefix="/users", tags=["用户"])


# response_model 响应结构中定义了from_attributes=True，允许从模型属性中创建响应结构
@router.post("/users", response_model=UserOut)
async def create_user(user: UserCreate):
    existing = await User.get_or_none(username=user.username)
    if existing:
        raise HTTPException(status_code=400, detail="邮箱已存在")

    user_obj = await User.create(**user.model_dump())
    return user_obj


@router.get("/user1/{user_id}", response_model=UserOut)
async def get_user1(user_id: int):
    user = await User.get_or_none(id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user


# 使用统一响应结构 的异常处理器
@router.get("/user2/{user_id}", response_model=UserOut)
async def get_user2(user_id: int):
    user = await User.get_or_none(id=user_id)
    if not user:
        raise BusinessException(code=4040, message="用户不存在")
    return user


# 使用自定义统一的响应结构Response 及使用 全局异常处理器
@router.get("/user3/{user_id}", response_model=Response[UserOut])
async def get_user3(user_id: int):
    user = await User.get_or_none(id=user_id)
    if not user:
        raise BusinessException(code=4040, message="用户不存在")
    return Response(data=user)


@router.get("/users/", response_model=Response[list[UserOut]])
async def get_users():
    users = await User.all()
    return Response(data=users)  # 返回统一响应结构


# 🔹 更新用户
@router.put("/{user_id}", response_model=Response[UserOut], summary="更新用户")
async def update_user(user_id: int, user: UserUpdate):
    user_obj = await User.get_or_none(id=user_id)
    if not user_obj:
        raise HTTPException(status_code=404, detail="用户不存在")
    user_data = user.model_dump(exclude_unset=True)
    for k, v in user_data.items():
        setattr(user_obj, k, v)
    await user_obj.save()
    return Response(data=user_obj)


# 🔹 删除用户
@router.delete("/{user_id}", summary="删除用户", response_model=Response[dict[str, str]])
async def delete_user(user_id: int):
    deleted_count = await User.filter(id=user_id).delete()
    if not deleted_count:
        raise HTTPException(status_code=404, detail="用户不存在")
    return Response(data={"message": "删除成功"})


# 用户注册 & 登录
@router.post("/register", response_model=UserOut)
async def register(user: UserCreate):
    default_role = await Role.get_or_create(name="user")  # 默认角色
    hashed_pwd = hash_password(user.password)
    role_obj, created = await Role.get_or_create(name="user")
    new_user = await User.create(username=user.username, hashed_password=hashed_pwd, role=role_obj)
    return new_user


@router.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = await authenticate_user(form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=401, detail="用户名或密码错误")
    return create_token_response(user.username)


@router.get("/me", response_model=UserOut)
async def get_me(current_user=Depends(get_current_user)):
    return current_user


# 🔹 角色权限控制
@router.get("/admin-only")
async def admin_route(current_user=Depends(require_role(["admin"]))):
    return {"msg": f"欢迎管理员 {current_user.username}"}


@router.get("/user")
async def user_route(current_user=Depends(require_role(["user", "admin"]))):
    return {"msg": f"欢迎用户 {current_user.username}"}

